package cn.xorange.love.common;

import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.utils.lang.StringUtils;
import cn.xorange.commons.utils.spring.SpringUtils;
import cn.xorange.love.common.exception.XoErrorCode;
import cn.xorange.love.common.exception.XoException;
import com.alibaba.fastjson2.JSON;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : yangjian
 * date : 2024/7/15
 * description :
 */
public class XoUtils {
    XoUtils(){}

    public static void checkCertAuthAttack(String type){
        long savaTime = (long) 24 * 3600;
        Long userId = SecurityUtils.getUserId();
        String key = StringUtils.format("cert:{}:{}", userId, type);
        Integer num = SpringUtils.getBean(ICacheService.class).getCacheObject(key);
        if(Objects.isNull(num)){
            num = 0;
        }
        if(num>=20){
            throw new XoException(XoErrorCode.AUTH_BLOCKED);
        }

        num = num + 1;
        SpringUtils.getBean(ICacheService.class).setCacheObject(key, num, savaTime, TimeUnit.SECONDS);

    }

    public static Long getOrangeId(){
        String userJson = SecurityUtils.getUserJson();
        return JSON.parseObject(userJson).getLong("orangeId");
    }
}
